<template>
  <view class="formContainer">
    <view v-if="query.isMine == 0 && query.mode === 'waiting'">
      <view class="divider divider-horizontal">
        <view class="text">以下是审核信息</view>
      </view>
      <uni-forms
        ref="valiForm"
        :rules="rules"
        v-model="formData"
        label-position="top"
        label-width="150"
      >
        <uni-forms-item label="审批" required name="status">
          <uni-data-checkbox
            mode="tag"
            v-model="formData.status"
            :localdata="aData"
            @change="onChange"
          />
        </uni-forms-item>
        <uni-forms-item
          label="驳回节点"
          required
          name="targetActivityId"
          v-if="formData.status == 3"
        >
          <uni-data-select
            v-model="formData.targetActivityId"
            :localdata="bData"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item
          label="选择人员"
          required
          name="userId"
          v-if="[1, 2, 5].indexOf(formData.status) !== -1"
        >
          <template v-slot:label>
            <view class="myLabel">
              <view><text class="star">*</text>选择人员</view>
              <uni-icons
                type="plus-filled"
                size="30"
                color="#409EFF"
                @click="onLocation(`/pages/user/select?${selUrlParam}`)"
              />
            </view>
          </template>
          <view
            :style="{
              color: formData.userName ? '#555' : '#888',
              marginTop: '10rpx',
            }"
            >{{ formData.userName || '点击右侧图标选择' }}</view
          >
          <!-- <uni-tag text="点击右侧图标选择" type="primary" /> -->
        </uni-forms-item>
        <uni-forms-item
          label="选择减签人员"
          required
          name="taskIds"
          v-if="formData.status == 6"
        >
          <view
            :style="{
              color: formData.taskIds.length !== 0 ? '#555' : '#888',
            }"
            @click="$refs.popup.open('bottom')"
            >{{
              formData.assigneeNames && formData.assigneeNames.length !== 0
                ? formData.assigneeNames.join()
                : '点击选择'
            }}</view
          >
        </uni-forms-item>
        <uni-forms-item label="审批意见" name="remark">
          <uni-easyinput
            type="textarea"
            v-model="formData.remark"
            placeholder="请输入"
          />
        </uni-forms-item>
      </uni-forms>
      <button class="btn" type="primary" @click="onSubmit('valiForm')">
        提交
      </button>
    </view>
    <view class="btnBox" v-if="query.isMine == 1">
      <button
        class="btn"
        type="warn"
        v-if="query.isMine == 1 && query.mode === 'edit_mode'"
        @click="onDelete"
      >
        删除
      </button>
      <button
        class="btn"
        type="warn"
        v-if="query.isMine == 1 && query.mode === 'waiting'"
        @click="onCancel"
      >
        撤销
      </button>
    </view>

    <uni-popup ref="popup" background-color="#fff">
      <view class="signList">
        <view class="title">减签人员</view>
        <checkbox-group @change="checkboxChange">
          <label class="signItem" v-for="item in cData" :key="item.id">
            <view class="uni-inline-item">
              <checkbox
                :value="item.id"
                :checked="formData.taskIds.indexOf(item.id) > -1"
              />
              <view>{{ item.assigneeName }}</view>
            </view>
            <view>{{ item.name }}</view>
          </label>
        </checkbox-group>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  getTaskById,
  backProcess,
  completeTask,
  transferTask,
  delegateTask,
  terminationTask,
  getTaskNodeList,
  addMultiInstance,
  delMultiInstance,
  cancelProcessApply,
  deleteRunAndHisInstance,
  getListByDeleteMultiInstance,
  getTaskUserIdsByAddMultiInstance,
} from '@/api/workOrder';
export default {
  data() {
    return {
      // 表单数据
      formData: {},
      // 规则
      rules: {
        status: {
          rules: [
            {
              required: true,
              errorMessage: '请选择审批操作',
            },
          ],
        },
        userId: {
          rules: [
            {
              required: true,
              errorMessage: '请选择人员',
            },
          ],
        },
        targetActivityId: {
          rules: [
            {
              required: true,
              errorMessage: '请选择节点',
            },
          ],
        },
        taskIds: {
          rules: [
            {
              required: true,
              errorMessage: '请选择减签人员',
            },
          ],
        },
      },
      // 字典数据
      aData: [
        {
          text: '通过',
          label: '通过',
          value: 0,
        },
        {
          text: '转办',
          label: '转办',
          value: 1,
        },
        {
          text: '委托',
          label: '委托',
          value: 2,
        },
        {
          text: '驳回',
          label: '驳回',
          value: 3,
        },
        {
          text: '终止',
          label: '终止',
          value: 4,
        },
      ],
      // 驳回节点
      bData: [],
      // 减签数据
      cData: [],
    };
  },
  props: {
    query: {
      type: Object,
      default: {},
    },
    show: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    'query.mode': {
      handler(newVal) {
        if (newVal === 'waiting') this.getData();
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    selUrlParam() {
      // url参数
      let obj = {
        multiple: 0,
      };
      if (this.formData.status === 5) {
        obj = {
          multiple: 1,
          excludeUserIds: this.excludeUserIds,
        };
      }
      return this.$util.jsonToUrlParam(obj);
    },
  },
  created() {
    this.$bus.on('addUserData', (res) => {
      if (res && res.length !== 0) {
        this.formData.userId = res.map((item) => item.userId).join();
        this.formData.userName = res.map((item) => item.nickName).join();
      }
    });
  },
  unmounted() {
    this.$bus.off('addUserData');
  },
  methods: {
    getData() {
      getTaskById(this.query.taskId).then((res) => {
        // multiInstance 加签 减签
        if (res.data.multiInstance) {
          this.aData.push(
            {
              text: '加签',
              value: 5,
            },
            {
              text: '减签',
              value: 6,
            }
          );
        }
        getTaskNodeList(res.data.processInstanceId).then((res) => {
          this.bData = res.data.map((item) => {
            return {
              label: item.nodeName,
              text: item.nodeName,
              value: item.nodeId,
            };
          });
        });
      });
    },
    // 审批项change
    onChange(e) {
      // 加签数据
      if (e.detail.value == 5) {
        getTaskUserIdsByAddMultiInstance(this.query.taskId).then((res) => {
          this.excludeUserIds = res.data;
        });
      }
      // 减签数据
      if (e.detail.value == 6) {
        this.formData.taskIds = [];
        getListByDeleteMultiInstance(this.query.taskId).then((res) => {
          this.cData = res.data;
        });
      }
    },
    // 减签checkbox
    checkboxChange(e) {
      let r = this.cData.filter((item) => e.detail.value.indexOf(item.id) > -1);
      // 赋值
      this.formData.taskIds = r.map((item) => item.id);
      this.formData.executionIds = r.map((item) => item.executionId);
      this.formData.assigneeIds = r.map((item) => item.assignee);
      this.formData.assigneeNames = r.map((item) => item.assigneeName);
    },
    // 提交
    onSubmit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          // loading提示
          uni.showLoading({ title: '操作中' });
          // 数据
          let params = {},
            api;
          if (this.formData.status == 0) {
            params = {
              taskId: this.query.taskId,
              message: this.formData.remark,
              variables: {},
              wfCopyList: [],
              messageType: ['1'],
            };
            api = completeTask;
          } else if (this.formData.status == 1) {
            params = {
              taskId: this.query.taskId,
              userId: this.formData.userId,
              comment: this.formData.remark,
            };
            api = transferTask;
          } else if (this.formData.status == 2) {
            params = {
              taskId: this.query.taskId,
              userId: this.formData.userId,
              nickName: this.formData.userName,
            };
            api = delegateTask;
          } else if (this.formData.status == 3) {
            params = {
              taskId: this.query.taskId,
              message: this.formData.remark,
              variables: {},
              messageType: ['1'],
              targetActivityId: this.formData.targetActivityId,
            };
            api = backProcess;
          } else if (this.formData.status == 4) {
            params = {
              taskId: this.query.taskId,
              comment: this.formData.remark,
            };
            api = terminationTask;
          } else if (this.formData.status == 5) {
            params = {
              taskId: this.query.taskId,
              assignees: this.formData.userId.split(','),
              assigneeNames: this.formData.userName.split(','),
            };
            api = addMultiInstance;
          } else if (this.formData.status == 6) {
            params = {
              taskId: this.query.taskId,
              taskIds: this.formData.taskIds,
              executionIds: this.formData.executionIds,
              assigneeIds: this.formData.assigneeIds,
              assigneeNames: this.formData.assigneeNames,
            };
            api = delMultiInstance;
          }
          // console.log('success', res, params);
          // 统一接口逻辑
          api(params).then((res) => {
            uni.hideLoading();
            uni.showToast({
              title: `操作成功`,
            });
            this.onBack();
          });
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    // 删除
    onDelete() {
      uni.showModal({
        title: '提示',
        content: '是否确认删除？',
        success: (res) => {
          if (res.confirm) {
            deleteRunAndHisInstance(this.query.businessKey).then((res) => {
              uni.showToast({
                title: `删除成功`,
              });
              this.onBack();
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    },
    // 撤销
    onCancel() {
      uni.showModal({
        title: '提示',
        content: '是否确认撤销？',
        success: (res) => {
          if (res.confirm) {
            cancelProcessApply(this.query.businessKey).then((res) => {
              uni.showToast({
                title: `撤销成功`,
              });
              this.onBack();
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    },
    // 跳转页面
    onLocation(url) {
      uni.navigateTo({
        url,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.formContainer {
  .myLabel {
    color: #606266;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .star {
      color: #dd524d;
    }
  }
  .btnBox {
    margin: 60rpx 0 10rpx;
  }
}
.signList {
  height: 40vh;
  padding: 36rpx;
  overflow: auto;
  .title {
    font-size: 40rpx;
    text-align: center;
    padding: 0 0 20rpx;
  }
  .signItem {
    padding: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 2rpx solid #e8e8e8;
  }
}
</style>
